package com.shelpe.services.algorithm.configuration;

import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import com.alibaba.druid.pool.DruidDataSource;

@Configuration
@EnableJpaRepositories(basePackages = "com.shelpe.services.algorithm.repository.jpa")
@EnableTransactionManagement
@MapperScan(basePackages = "com.shelpe.services.algorithm.repository.batis")
public class DBConfiguration {

	@Bean
    public DataSource dataSource(DataSourceProperties props) {
		DruidDataSource ds = new DruidDataSource();
		if(props != null){
			ds.setDriverClassName(props.getDriverClassName());
			ds.setUrl(props.getUrl());
			ds.setUsername(props.getUsername());
			ds.setPassword(props.getPassword());
		}
        return ds;
    }
	
	
	@Bean
	public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
		SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
		sqlSessionFactoryBean.setDataSource(dataSource);

		PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();

		sqlSessionFactoryBean.setMapperLocations(resolver.getResources("classpath:/sqlmaps/*.xml"));
		return sqlSessionFactoryBean.getObject();
	}
}
